package es

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/elastic/go-elasticsearch/esapi"
	"log"
	"shop_srv/goods"
	"shop_srv/model/mysql"
	"strconv"
	"strings"
)

func SyncGoods(goods *mysql.Goods) {
	str, _ := json.Marshal(goods)

	req := esapi.IndexRequest{
		Index:      "goods",
		DocumentID: strconv.Itoa(int(goods.ID)),
		Body:       strings.NewReader(string(str)),
		Refresh:    "true",
	}
	// Perform the request with the client.
	res, err := req.Do(context.Background(), es)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()
}

func GoodsSearch(keyword string) {

	var query map[string]interface{}
	if keyword == "" {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match_all": map[string]interface{}{},
			},
		}
	} else {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match": map[string]interface{}{
					"GoodsTitle": keyword,
				},
			},
		}
	}
	str, err := json.Marshal(query)
	res, err := es.Search(
		es.Search.WithContext(context.Background()),
		es.Search.WithIndex("goods"),
		es.Search.WithBody(strings.NewReader(string(str))),
		es.Search.WithTrackTotalHits(true),
		es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("ERROR: %s", err)
	}
	fmt.Println(res)

	var r map[string]interface{}
	json.NewDecoder(res.Body).Decode(&res)
	var goodsList []*goods.GetGoods

	// Print the ID and document source for each hit.
	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		source := hit.(map[string]interface{})["_source"]
		fmt.Println(source)
		goodsList = append(goodsList, &goods.GetGoods{
			GoodsTitle:  source.(map[string]interface{})["GoodsTitle"].(string),
			GoodsPrice:  int64(source.(map[string]interface{})["GoodsPrice"].(float64)),
			GoodsStock:  int64(source.(map[string]interface{})["GoodsStock"].(float64)),
			GoodsCover:  source.(map[string]interface{})["GoodsCover"].(string),
			GoodsStatus: int64(source.(map[string]interface{})["GoodsPrice"].(float64)),
		})
	}
	fmt.Println(goodsList)
	fmt.Println()
}
